//
//  CCLockViewController.m
//  cc
//
//  Created by ZLQ on 2016/10/27.
//  Copyright © 2016年 hbyj. All rights reserved.
//

#import "CCLockViewController.h"
#import "WJTouchID.h"
#import "MainViewController.h"
#import "LockView.h"
#import "CCGeRenZhongXinController.h"
#import "MainViewController.h"
@interface CCLockViewController ()<WJTouchIDDelegate,LockViewDelegate>
{
    UIImageView * imageView;
}
@property(nonatomic,weak)UILabel *unlocklabel;
@property(nonatomic,weak)UILabel *setpassword;
//标记是否是重置密码
@property(nonatomic ,assign,getter=isresetpassword)BOOL resetpassword;
//判断是否是两次确认密码
@property(nonatomic,assign,getter=istwopassword)BOOL twopassword;

@property(weak,nonatomic)LockView *lockview;

@end

@implementation CCLockViewController

-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    UIImageView *imgV = [[UIImageView alloc] initWithFrame:SCREEN];
    imgV.image = [UIImage imageNamed:@"zabj"];
    [self.view addSubview:imgV];
    //UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap)];
    imgV.userInteractionEnabled = YES;
    //[imgV addGestureRecognizer:tap];
    
    
    [[WJTouchID touchID] startWJTouchIDWithMessage:WJNotice(@"请指纹解锁", @"The Custom Message") fallbackTitle:WJNotice(@"按钮标题", @"Fallback Title") delegate:self];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(lock) name:@"Lock" object:nil];
}
//解锁通知
-(void)lock{
    [self changeView];
}

//图片的点击事件
-(void)tap1{
    [[WJTouchID touchID] startWJTouchIDWithMessage:WJNotice(@"请指纹解锁", @"The Custom Message") fallbackTitle:WJNotice(@"按钮标题", @"Fallback Title") delegate:self];
}

// 指纹验证成功 事件
- (void) WJTouchIDAuthorizeSuccess {
    MainViewController *root=[[MainViewController alloc]init];
    UIApplication.sharedApplication.delegate.window.rootViewController = root;
}

/**
 *  TouchID验证失败
 *
 *  Authentication Failure
 */
- (void) WJTouchIDAuthorizeFailure {
    
    [self performSelector:@selector(changeView) withObject:self afterDelay:2];
    
}

/**
 *  用户点击了取消按钮
 *
 *  Authentication Failure
 */
- (void) WJTouchIDAuthorizeErrorUserCancel {

    //[self performSelector:@selector(changeView) withObject:self afterDelay:2];
    
}

/**
 *  在TouchID对话框中点击输入密码按钮
 *
 *  User tapped the fallback button
 */
- (void) WJTouchIDAuthorizeErrorUserFallback {

    //    RootViewController *root=[[RootViewController alloc]init];
    //    UIApplication.sharedApplication.delegate.window.rootViewController = root;
    
}

/**
 *  在验证的TouchID的过程中被系统取消 例如突然来电话、按了Home键、锁屏...
 *
 *  Authentication was canceled by system (e.g. another application went to foreground).
 */
- (void) WJTouchIDAuthorizeErrorSystemCancel {
    
    [self performSelector:@selector(changeView) withObject:self afterDelay:2];
    
}

/**
 *  无法启用TouchID,设备没有设置密码
 *
 *  Authentication could not start, because passcode is not set on the device.
 */
- (void) WJTouchIDAuthorizeErrorPasscodeNotSet {
    [self performSelector:@selector(changeView) withObject:self afterDelay:2];
}

/**
 *  设备没有录入TouchID,无法启用TouchID
 *
 *  Authentication could not start, because Touch ID has no enrolled fingers
 */
- (void) WJTouchIDAuthorizeErrorTouchIDNotEnrolled {
    [self performSelector:@selector(changeView) withObject:self afterDelay:2];
    
}

/**
 *  该设备的TouchID无效
 *
 *  Authentication could not start, because Touch ID is not available on the device.
 */
- (void) WJTouchIDAuthorizeErrorTouchIDNotAvailable {
    [self performSelector:@selector(changeView) withObject:self afterDelay:2];
    
}


/**
 *  多次连续使用Touch ID失败，Touch ID被锁，需要用户输入密码解锁
 *
 *  Authentication was not successful, because there were too many failed Touch ID attempts and Touch ID is now locked. Passcode is required to unlock Touch ID, e.g. evaluating LAPolicyDeviceOwnerAuthenticationWithBiometrics will ask for passcode as a prerequisite.
 *
 */
- (void) WJTouchIDAuthorizeLAErrorTouchIDLockout {
    [self performSelector:@selector(changeView) withObject:self afterDelay:2];
    
}

/**
 *  当前软件被挂起取消了授权(如突然来了电话,应用进入前台)
 *
 *  Authentication was canceled by application (e.g. invalidate was called while authentication was inprogress).
 *
 */
- (void) WJTouchIDAuthorizeLAErrorAppCancel {
    [self performSelector:@selector(changeView) withObject:self afterDelay:2];
}

/**
 *  当前软件被挂起取消了授权 (授权过程中,LAContext对象被释)
 *
 *  LAContext passed to this call has been previously invalidated.
 */
- (void) WJTouchIDAuthorizeLAErrorInvalidContext {
    [self performSelector:@selector(changeView) withObject:self afterDelay:2];
}
/**
 *  当前设备不支持指纹识别
 *
 *  The current device does not support fingerprint identification
 */
-(void)WJTouchIDIsNotSupport {
    [self performSelector:@selector(changeView) withObject:self afterDelay:2];
    
}


-(void)changeView
{
    
    imageView.image=[UIImage imageNamed:@"zabj"];
    
    self.view.backgroundColor =[UIColor whiteColor];
    
    _unlocklabel.font=[UIFont fontWithName:@"Hiragino Sans GB" size:14];
    _setpassword.font=[UIFont fontWithName:@"Hiragino Sans GB" size:14];

    
    UIImageView *logoimage=[[UIImageView alloc]init];
    logoimage.frame=CGRectMake(WIDTH/2-40, 60, 80, 80);
    logoimage.image=[UIImage imageNamed:@"nvpengyou"];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap1)];
    [logoimage addGestureRecognizer:tap];
    logoimage.userInteractionEnabled = YES;
    
    logoimage.layer.cornerRadius=40;
    logoimage.layer.masksToBounds=YES;
    [self.view addSubview:logoimage];
    
    UILabel *jieSuoLabel = [[UILabel alloc] initWithFrame:CGRectMake(logoimage.cc_centerX-50, CGRectGetMaxY(logoimage.frame), 100, 40)];
    jieSuoLabel.text = @"点击头像指纹解锁";
    jieSuoLabel.textColor = [UIColor lightGrayColor];
    jieSuoLabel.textAlignment = NSTextAlignmentCenter;
    jieSuoLabel.font = [UIFont systemFontOfSize:12];
    [self.view addSubview:jieSuoLabel];
  
    
    [super viewDidLoad];

    
    self.resetpassword = NO;
    self.twopassword = NO;
    LockView *lockview = [[LockView alloc]init];
    lockview.backgroundColor = [UIColor clearColor];
    lockview.cc_width = 300;
    lockview.cc_height = 300;
    lockview.cc_x = (WIDTH - lockview.cc_width) * 0.5;
    lockview.cc_y = 200;
    self.lockview = lockview;
    lockview.delegate = self;
    [self.view addSubview:lockview];
    
    //    self.view.backgroundColor=[UIColor redColor];
    self.lockview.delegate = self;
    
    
    [self judgeMentLocalPassWord];
    
    [self jinrudengluzhucejiemian];
    

}



//设置状态栏颜色
- (UIStatusBarStyle)preferredStatusBarStyle{
    
    return UIStatusBarStyleLightContent;
}

-(void)jinrudengluzhucejiemian
{
    UIButton *resetpassword = [[UIButton alloc]init];
    [resetpassword setTitle:@"账号登陆" forState:UIControlStateNormal];
    [resetpassword setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    resetpassword.titleLabel.font=[UIFont fontWithName:@"Hiragino Sans GB" size:14];
    //    [resetpassword setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [resetpassword sizeToFit];
    resetpassword.cc_y = CGRectGetMaxY(self.lockview.frame) + 20;
    resetpassword.cc_x = (WIDTH - resetpassword.cc_width) * 0.8;
    [self.view addSubview:resetpassword];
    [resetpassword addTarget:self action:@selector(resetPassWorde) forControlEvents:UIControlEventTouchUpInside];

}

-(void)resetPassWorde
{
    CCGeRenZhongXinController *logView=[[CCGeRenZhongXinController alloc]init];
    //logView.pd=@"1";
    logView.shifoujiesouyemiandenglu = @"YES";
    [self presentViewController:logView animated:YES completion:nil];
    //[self.navigationController pushViewController:logView animated:YES];
}

//添加重置密码按钮
- (void)addResetPassWordBuutton{
    UIButton *resetpassword = [[UIButton alloc]init];
    [resetpassword setTitle:@"重置密码" forState:UIControlStateNormal];
    resetpassword.titleLabel.font=[UIFont fontWithName:@"Hiragino Sans GB" size:14];
    [resetpassword setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    
    [resetpassword sizeToFit];
    resetpassword.cc_y = CGRectGetMaxY(self.lockview.frame) + 20;
    resetpassword.cc_x = (WIDTH - resetpassword.cc_width) * 0.2;
    [self.view addSubview:resetpassword];
    [resetpassword addTarget:self action:@selector(resetPassWord) forControlEvents:UIControlEventTouchUpInside];
    
}
//添加下次设置按钮
- (void)addCancelButton{
    UIButton *cancelbutt = [[UIButton alloc]init];
    [cancelbutt setTitle:@"指纹解锁" forState:UIControlStateNormal];
    cancelbutt.titleLabel.font=[UIFont fontWithName:@"Hiragino Sans GB" size:14];
    
    [cancelbutt setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    
    [cancelbutt sizeToFit];
    cancelbutt.cc_y = CGRectGetMaxY(self.lockview.frame) + 20;
    cancelbutt.cc_x = (WIDTH - cancelbutt.cc_width) * 0.2;
    [self.view addSubview:cancelbutt];
    [cancelbutt addTarget:self action:@selector(cancelButtonClick) forControlEvents:UIControlEventTouchUpInside];
    
}

//添加重置密码和取消设置的按钮
//- (void)addResetPassWordButtAndCancelButt{
//
//    UIButton *resetpassword = [[UIButton alloc]init];
//    [resetpassword setTitle:@"重置密码" forState:UIControlStateNormal];
//    [resetpassword setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
//    [resetpassword sizeToFit];
//    resetpassword.y = 500;
//    resetpassword.x = 80;
//    [self.view addSubview:resetpassword];
//    [resetpassword addTarget:self action:@selector(resetPassWord) forControlEvents:UIControlEventTouchUpInside];
//
//
//    UIButton *cancelbutt = [[UIButton alloc]init];
//    [cancelbutt setTitle:@"下次设置" forState:UIControlStateNormal];
//    [cancelbutt setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
//    [cancelbutt sizeToFit];
//    cancelbutt.y = 500;
//    cancelbutt.x = CGRectGetMaxX(resetpassword.frame) + 50;
//    [self.view addSubview:cancelbutt];
//    [cancelbutt addTarget:self action:@selector(cancelButtonClick) forControlEvents:UIControlEventTouchUpInside];
//
//}

//取消设置按钮
- (void)cancelButtonClick{
    
    //[self dismissViewControllerAnimated:YES completion:nil];
    /*
    [UIApplication sharedApplication].keyWindow.rootViewController = self;
    
    [[WJTouchID touchID] startWJTouchIDWithMessage:WJNotice(@"请指纹解锁", @"The Custom Message") fallbackTitle:WJNotice(@"按钮标题", @"Fallback Title") delegate:self];
    */
}

//重置按钮点击事件
- (void)resetPassWord{
    self.resetpassword = YES;
    [self setLocklabel:@"确认旧手势密码"];
    [self.unlocklabel sizeToFit];
    self.unlocklabel.cc_x = (WIDTH - self.unlocklabel.cc_width) * 0.5;
    self.unlocklabel.cc_y = CGRectGetMinY(self.lockview.frame) - 40;
    
}

//lockview的代理方法
- (BOOL)unlockView:(LockView *)unlockView withPassword:(NSString *)password
{
    NSString *localpasswordone = [[NSUserDefaults standardUserDefaults]objectForKey:@"passwordone"];
    NSString *localpasswordtwo = [[NSUserDefaults standardUserDefaults]objectForKey:@"passwordtwo"];
    
    if (self.twopassword) {
        if ([localpasswordone isEqualToString:localpasswordtwo]) {
            
            NSLog(@"%@",localpasswordone);
            
            UIAlertView *confirmalertview = [[UIAlertView alloc]initWithTitle:@"密码设置成功" message:@"请输入密码解锁" delegate:self cancelButtonTitle:@"确认" otherButtonTitles:nil, nil];
            [confirmalertview show];
            [self setLocklabel:@"手势解锁"];
            self.twopassword = NO;
            //            if ([self.czmm isEqualToString:@"1"]) {
            //                [self dismissViewControllerAnimated:YES completion:^{
            //
            //
            //
            //                }];
            //
            //            }
            
            
            return YES;
        }
        
        else
        {
            UIAlertView *alertview = [[UIAlertView alloc]initWithTitle:@"与上次密码不对应" message:@"请重新设置密码" delegate:self cancelButtonTitle:@"确认" otherButtonTitles:nil, nil];
            [alertview show];
            [[NSUserDefaults standardUserDefaults]removeObjectForKey:@"passwordone"];
            [[NSUserDefaults standardUserDefaults]removeObjectForKey:@"passwordtwo"];
            [self setLocklabel:@"设置密码"];
            return NO;
        }
    }
    
    else
        
    {
        if ([password isEqualToString:localpasswordone]) {
            if (self.isresetpassword) {
                [[NSUserDefaults standardUserDefaults]removeObjectForKey:@"passwordone"];
                [[NSUserDefaults standardUserDefaults]removeObjectForKey:@"passwordtwo"];
                [self setLocklabel:@"设置新密码"];
                UIAlertView *resetalertview = [[UIAlertView alloc]initWithTitle:@"密码确认成功" message:@"请重新设置密码" delegate:self cancelButtonTitle:@"确认" otherButtonTitles:nil, nil];
                [resetalertview show];
                self.resetpassword = NO;
            }
            else
            {
                
                if ([self.czmm isEqualToString:@"0"]) {
                    [self dismissViewControllerAnimated:YES completion:^{
   
                    }];
                    
                }else{
                    
                    
                    MainViewController *root=[[MainViewController alloc]init];
                    UIApplication.sharedApplication.delegate.window.rootViewController = root;
                    
                }
                
            }
            return YES;
        }
        else {
            return NO;
        }
        return NO;
    }
}

- (void)setPassWordSuccess:(NSString *)tabelname{
    NSString *localpasswordone = [[NSUserDefaults standardUserDefaults]objectForKey:@"passwordone"];
    NSString *localpasswordtwo = [[NSUserDefaults standardUserDefaults]objectForKey:@"passwordywo"];
    if (!localpasswordtwo||!localpasswordone ) {
        self.twopassword = YES;
    }
    self.setpassword.text = tabelname;
    self.unlocklabel.text = tabelname;
    [self.unlocklabel sizeToFit];
    [self.setpassword sizeToFit];
    self.setpassword.cc_x = (WIDTH - self.setpassword.cc_width) * 0.5;
    self.setpassword.cc_y = CGRectGetMinY(self.lockview.frame) - 20;
    self.unlocklabel.cc_x = (WIDTH - self.unlocklabel.cc_width) * 0.5;
    self.unlocklabel.cc_y = CGRectGetMinY(self.lockview.frame) - 20;
    
}

//判断本地是否存有密码
- (void)judgeMentLocalPassWord{

    NSString *password = [[NSUserDefaults standardUserDefaults]objectForKey:@"passwordone"];
    if (password == nil) {
        //添加下次设置按钮
        [self addCancelButton];
        [self setPassWordView:@"设置手势密码"];
    }else{
        //添加重置密码按钮
        [self addResetPassWordBuutton];
        [self unlockView:@"手势解锁"];
    }
    
}

//设置密码界面
- (void)setPassWordView:(NSString *)lockstr{
    UILabel *locklabel = [[UILabel alloc]init];
    locklabel.text = lockstr;
    locklabel.textAlignment = NSTextAlignmentCenter;
    self.setpassword = locklabel;
    locklabel.textColor = [UIColor grayColor];
    locklabel.font=[UIFont fontWithName:@"Hiragino Sans GB" size:12];
    [locklabel sizeToFit];
    locklabel.cc_x = (WIDTH - locklabel.cc_width) * 0.5;
    locklabel.cc_y = CGRectGetMinY(self.lockview.frame) - 20;
    [self.view addSubview:locklabel];
}

- (void)setLocklabel:(NSString *)locklstr{
    
    self.setpassword.text = locklstr;
    self.unlocklabel.text = locklstr;
    [self.setpassword sizeToFit];
    [self.unlocklabel sizeToFit];
    self.setpassword.cc_x = (WIDTH - self.setpassword.cc_width) * 0.5;
    self.setpassword.cc_y = CGRectGetMinY(self.setpassword.frame) - 20;
    self.unlocklabel.cc_x = (WIDTH - self.unlocklabel.cc_width) * 0.5;
    self.unlocklabel.cc_y = CGRectGetMinY(self.lockview.frame) - 20;
    [self.view addSubview:self.setpassword];
    [self.view addSubview:self.unlocklabel];
    
}

//手势解锁界面
- (void)unlockView:(NSString *)unlockstr{
    UILabel *locklabel = [[UILabel alloc]init];
    self.unlocklabel = locklabel;
    locklabel.text = unlockstr;
    locklabel.textColor = [UIColor grayColor];
    locklabel.font=[UIFont fontWithName:@"Hiragino Sans GB" size:12];
    
    [locklabel sizeToFit];
    locklabel.cc_x = (WIDTH - locklabel.cc_width) * 0.5;
    locklabel.cc_y = CGRectGetMinY(self.lockview.frame) - 20;
    [self.view addSubview:locklabel];
}


@end
